import React, { useState } from 'react'
import Message from '../../components/Message';
import AppDialog from '../../components/AppDialog'
import { Button, Form, Input, Space } from 'antd';
import { addAttrVals } from "../../api/params.js";

const AddAttrVals = (props) => {
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm();
  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true)
    let list = [...props.attrInfo.attr_vals, values.content]
    const obj = {
      attr_name: props.attrInfo.attr_name,
      attr_sel: props.attrInfo.attr_sel,
      attr_vals: list.join(" "),
    };
    await addAttrVals(props.cateId, props.attrInfo.attr_id, obj).finally(() => {
      setLoading(false)
    });
    Message("success", "添加成功")

    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    props.onHide(type)
  };

  return ( props.visible ? 
    <AppDialog
      title={`添加${props.titleText}${props.attrInfo != null ? props.attrInfo.attr_name : ''}的内容`}
      visible={props.visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="标签内容"
          name="content"
          rules={[{ required: true, message: '请输入内容' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>确定</Button>
            <Button onClick={() => handleDialogClosed()}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default AddAttrVals
